package com.han.singleton.demo7;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

/**
 * @ClassName Client
 * @Description 序列化反序列化破坏单例
 * @Author duoduo Han
 * @Date 2024/6/3 15:43
 */
public class Client {
    public static void main(String[] args) throws Exception {
//        writeObj2File();
        readObjFromFile();
        readObjFromFile();
    }

    // 向文件中写数据（对象）
    public static void writeObj2File() throws Exception {
        //1. 获取Singleton对象
        Singleton singleton = Singleton.getInstance();
        //2. 创建对象输出流对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("./singleton.txt"));
        //3. 写对象
        oos.writeObject(singleton);
        //4. 释放资源
        oos.close();
    }


    //从文件中读取数据（对象）
    public static void readObjFromFile() throws Exception {
        //1. 创建对象输入流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("./singleton.txt"));
        //2. 读取对象
        Singleton singleton = (Singleton) ois.readObject();
        System.out.println(singleton);
        //3. 释放资源
        ois.close();
    }

}
